// pages/nearby/nearby.js
const app = getApp()
let request = require("../../utils/request.js");
let config = require('../../config/config.js')
var QQMapWx = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({
  key: config.map_key
})
let flag = true
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: 0,
    longitude: 0,
    latitude: 0,
    parkList: [],
    page: 1,
    pageSize: 10,
    isCanNext: true,
    canIUseGetUserProfile: false,
    nearbyBarIndex: 0,
    bannerList: [],
    ticketList: [],
    productList: [],
    merchantList: [],
    token: wx.getStorageSync('lmtc_token')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('token:', this.data.token)
    console.log('token:', this.data.token == '')
    console.log('token:', this.data.token != null && this.data.token != '')
    
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // 获取屏幕高度
    this.setData({
      screenHeight: wx.getSystemInfoSync().screenHeight,
      token: wx.getStorageSync('lmtc_token')
    })
    this.getUserLocation()
  },
    /**
   * 授权登录
   */
  bindGetUserInfo: function (e) {
    console.log('授权登录')
    let that = this;
    // let url = e.currentTarget.dataset.url
    let userInfo = e.detail.userInfo;
    wx.setStorageSync('lmtc_userInfo', userInfo)
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
      wx.login({
        success: res => {
          that.getToken(res.code);
        }
      });
    }
  },
  /**
   * 顶部导航栏按钮
   */
  selectNearbyBar(e) {
    let index = e.currentTarget.dataset.index
    if (index == this.data.nearbyBarIndex) {
      return
    }
    this.setData({
      nearbyBarIndex: index
    })
  },
  /**
   * swiper组件滑动切换事件
   */
  changeNearbyBar(e) {
    let index = e.detail.current
    this.setData({
      nearbyBarIndex: index
    })
  },
  /**
   * 获取用户当前位置
   */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        });
        that.getParks(longitude, latitude);
        that.getNearbyBanner();
        that.getNearbyTicket();
        that.getNearbyProduct();
        that.getNearbyMerchant();
      }
    })
  },
  /**
   * 获取轮播图
   */
  getNearbyBanner() {
    let that = this
    let parmas = {
      longitude: that.data.longitude,
      latitude: that.data.latitude
    }
    request.http('/shop/shop-info/getNearShopGoodsSlideList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            bannerList: data.data
          })
        }
      })
  },
  /**
   * 点击轮播图事件
   */
  clickBannerImg(e) {
    let index = e.currentTarget.dataset.index
    let bannerList = this.data.bannerList
    console.log(index, bannerList);
  },
  /**
   * 获取附近优惠券
   */
  getNearbyTicket() {
    let that = this
    let parmas = {
      longitude: that.data.longitude,
      latitude: that.data.latitude
    }
    request.http('/shop/shop-info/getNearShopTicketList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            ticketList: data.data
          })
        }
      })
  },
  /**
   * 领取优惠券
   */
  getCoupon(e) {
    let index = e.currentTarget.dataset.index
    let ticketList = this.data.ticketList
    request.http('/customer/ticket/receive-ticket', 'POST', { ticketId: ticketList[index].id })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          wx.showToast({
            title: '领取成功',
          })
        }
      })
  },
  /**
   * 获取附近商品
   */
  getNearbyProduct() {
    let that = this
    let parmas = {
      longitude: that.data.longitude,
      latitude: that.data.latitude
    }
    request.http('/shop/shop-info/getNearShopGoodsList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let productList = data.data
          that.setData({
            productList
          })
        }
      })
  },
  /**
   * 购买商品页
   */
  productBuy(e) {
    let goods = e.currentTarget.dataset.item
    console.log('商品信息：', goods)
    // let productList = this.data.productList
    // console.log('商品信息：', productList[index])
    wx.navigateTo({
      url: '/pages/productOrderRecord/productOrderRecord?id='+goods.id,
      success() {
        // wx.setStorageSync('productInfo', goods)
      }
    })
  },
  /**
   * 获取附近商家
   */
  getNearbyMerchant() {
    let that = this
    let parmas = {
      longitude: that.data.longitude,
      latitude: that.data.latitude
    }
    request.http('/shop/shop-info/getNearShopInfoList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let merchantList = data.data
          let merchantListDistances = []
          for (var i = 0; i < merchantList.length; i++) {
            merchantListDistances.push({
              longitude: merchantList[i].longitude,
              latitude: merchantList[i].latitude
            })
          }
          that.calculateDistance(
            {
              longitude: that.data.longitude,
              latitude: that.data.latitude
            },
            merchantListDistances,
            function (res) {
              let data = res.result.elements
              let distances
              for (var j = 0; j < data.length; j++) {
                distances = (data[j].distance / 1000).toFixed(2)
                merchantList[j]['distances'] = distances
                that.setData({
                  merchantList
                })
              }
            }
          )
        }
      })
  },
  /**
  * 计算两点之间距离
  * @param {Object} from 起始位置经纬度
  * @param {Array} to 终点位置经纬度
  * @param {Function} callback 回调函数
  */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 在地图中打开
   */
  toMap(e) {
    let index = e.currentTarget.dataset.index
    let merchantList = this.data.merchantList
    wx.openLocation({
      latitude: merchantList[index].latitude * 1,
      longitude: merchantList[index].longitude * 1,
      name: merchantList[index].shopName,
      address: merchantList[index].shopAddress,
    })
  },
  /**
 * 获取用户信息
 */
  getUserProfile(e) {
    let that = this;
    let index = e.currentTarget.dataset.index
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.setData({
          userInfo: res.userInfo
        })
        wx.setStorageSync('lmtc_userInfo', res.userInfo)
        wx.login({
          success: res => {
            that.getToken(res.code, index);
          }
        });
      }
    })
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   * @param {Number} index 当前专属停车按钮索引
   */
  getToken(code) {
    let that = this
    let info = this.data.userInfo;
    let url = '/customer/info/authorize'
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
    }
    request.http(url, 'POST', params)
      .then(res => {
        var data = res.data
        if (data.code == 200) {
          let token = data.data.token
          // let parkData = this.data.parkList[index]
          wx.setStorageSync('lmtc_token', token)
          wx.setStorageSync('lmtc_customerId', data.data.customerId)
          that.setData({
            token: token
          })
          // wx.navigateTo({
          //   url: '../vipCharge/vipCharge?parkData=' + JSON.stringify(parkData) + '&index=1',
          // })
        }
      })
  },
  /**
   * 触底加载
   */
  scrollTolower() {
    if (!flag) {
      return
    }
    flag = false
    this.setData({
      page: this.data.page + 1
    })
    this.getParks(this.data.longitude, this.data.latitude)
  },
  /**
   * 获取附近停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getParks(longitude, latitude) {
    if (!this.data.isCanNext) {
      return
    }
    let that = this;
    let params = {
      longitude: longitude,
      latitude: latitude,
      currentPage: that.data.page,
      pageSize: that.data.pageSize
    }
    let url = "/park/info/getNearbyParkList";
    request.http(url, 'GET', params)
      .then((res) => {
        if (res.data.code == 200) {
          let parkLists = that.data.parkList
          let parkList = res.data.data.records;
          let parkNearby = []
          if (parkList.length <= 0) {
            that.setData({
              isCanNext: false
            })
          }
          for (var i = 0; i < parkList.length; i++) {
            parkNearby.push({
              longitude: parkList[i].longitude,
              latitude: parkList[i].latitude,
            })
          }
          that.calculateDistance(
            {
              longitude: longitude,
              latitude: latitude,
            },
            parkNearby,
            function (res) {
              let data = res
              if (data.status == 0) {
                let distance = data.result.elements[0].distance
                for (var i = 0; i < parkList.length; i++) {
                  parkList[i].distances = (distance / 1000).toFixed(2)
                }
                parkLists = parkLists.concat(parkList)
                that.setData({
                  parkList: parkLists
                })
              }
            }
          )
          // parkLists = parkLists.concat(parkList)
          // that.setData({
          //   parkList: parkLists
          // })
          flag = true
        }
      })
  },
  /**
   * 跳转到会员中心
   * @param {*} e 
   */
  toVip(e) {
    let index = e.currentTarget.dataset.index
    let parkData = this.data.parkList[index]
    wx.navigateTo({
      url: '/pages/pay/monthly/monthly?parkData=' + JSON.stringify(parkData),
    })
  },
  /**
   * 在地图中打开
   * @param {*} e 
   */
  toMapNavigation(e) {
    let index = e.currentTarget.dataset.index
    let parkData = this.data.parkList[index]
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
 * 计算两点之间距离
 * @param {Object} from 起始位置经纬度
 * @param {Array} to 终点位置经纬度
 * @param {Function} callback 回调函数
 */
  calculateDistance(from, to, callback) {
    if (to.length <= 0) {
      return
    }
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
})